package org.javanile.young;

import java.io.*;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author cicciodarkast
 */
public class Smal {

	public class Const {
		public static final int BEGIN	= 0;
		public static final int INNER	= 1;
		public static final int HEADER	= 2;
	}

	public class Fragment {
		private byte[] bytecode;
		private int	index;
		public void append(byte[] bc, int length) {
			for(int i=0;i<length;i++) {
				bytecode[index+i] = bc[i];
			}
			index+=length;
		}
		public byte[] load() {
			return bytecode;
		}
		public Fragment() {
			index = 0;
			bytecode = new byte[1000];
		}
		public int size() {return index;}
		public int end() {
			return 0;
		}
	}

	public Fragment parseList(String code, int offset) {
		int i = offset;
		int status = Const.BEGIN;
		Fragment f = new Fragment();
		String header = "";
		while(i<code.length()) {
			char c = code.charAt(i);
			switch(status) {
				case Const.BEGIN:switch(c) {
					case '(':status=Const.INNER;break;
					case ' ':break;
					default:status=Const.HEADER;header+=c;break;
				}break;
				case Const.HEADER:switch(c) {
					case '(':status=Const.INNER;break;
					default:status=Const.HEADER;header+=c;break;
				}break;
			}
			i++;
			switch(status) {
				case Const.INNER:Fragment y=parseList(code,i);i=y.end();f.append(y.load(),y.size());break;
			}
		}
		return f;
	}

    public Smal() {}

    public void init() {

        String code = readHelpText();
        System.out.println("FILE: "+code);

		Fragment bytecode = new Fragment();
        int c = 0;
        while(c<0) {
            Fragment f = parseList(code,c);
			bytecode.append(f.load(), f.size());
			c = f.end();
        }


		bytecode.load();





    }


     private String readHelpText()
  {
    InputStream is = getClass().getResourceAsStream("kernel.smal");
    try
    {
      StringBuffer sb = new StringBuffer();
      int chr, i = 0;
      // Read until the end of the stream
      while ((chr = is.read()) != -1)
          sb.append((char) chr);

      return sb.toString();
    }
    catch (Exception e)
    {
      System.out.println("Unable to create stream");
    }
    return null;
  }
}
